<!--  -->
<template>
  <div class="fixed left-0 top-0 z-20" ref="ChartCenter1" id="map"></div>
  <div class="absolute bottom-3 right-0 border-2 bg-[#ACC6D5] bg-opacity-5 border-[#19AEEF]/30 p-4">
    <div v-for="(item, index) in tabs" :key="index" class="flex items-center justify-between h-8">
      <img class="w-4 h-5 mr-2" :src="item.icon" alt="" />
      <div>{{ item.label }}</div>
      <div class="w-6 text-end">{{ item.value }}</div>
    </div>
  </div>
  <div
    class="absolute top-16 left-0 px-4 flex bg-[url(@/assets/rect77.png)] bg-contain w-[202px] h-[42px] justify-between items-center pointer-events-auto z-50 cursor-pointer"
    @click="returnToNormal"
  >
    <div class="">今日取号量</div>
    <div class="flex items-center justify-end">
      <span class="text-2xl text-[#52d98b] family-bold mr-1">
        <NumberGrowWarp :value="todayCount"></NumberGrowWarp> </span
      >个
    </div>
  </div>
  <DialogBox title="点位监控" :show="showDialog" @close="showDialog = false">
    <LineVideo :url="videoUrl"></LineVideo>
  </DialogBox>

  <DialogBox
    :title="(showGetCheck ? '取号量' : '排队数') + '排行'"
    :show="showMapOrder"
    @close="
      () => {
        selectName = ''
        showMapOrder = false
      }
    "
  >
    <div class="flex justify-end">
      <button class="gl-normal-button px-2 py-1" v-if="showGetCheck" @click="showGetCheck = false">
        排队情况 <el-icon><ArrowRight /></el-icon>
      </button>
      <button class="gl-normal-button px-2 py-1" v-else @click="showGetCheck = true">
        取票情况 <el-icon><ArrowRight /></el-icon>
      </button>
    </div>
    <transition enter-active-class="animate__animated animate__fadeIn">
      <TicketQuantityComp
        v-if="showGetCheck"
        :region-name="regionName"
        :select-point="selectPoint!"
      ></TicketQuantityComp>
    </transition>
    <transition enter-active-class="animate__animated animate__fadeIn">
      <TicketGetComp
        v-if="!showGetCheck"
        :region-name="regionName"
        :select-point="selectPoint!"
        :selectID="selectPointID"
      ></TicketGetComp>
    </transition>
  </DialogBox>
</template>

<script setup lang="ts">
import { requestApi } from '@/api'
import ic_lv from '@/assets/mapIcon.svg'
import ic_zong from '@/assets/mapIcon_business.svg'
import ic_huang from '@/assets/mapIcon_city.svg'
import wuJiangJson from '@/assets/wujiang.json'
import DialogBox from '@/components/box/DialogBox.vue'
import LineVideo from '@/components/line-video/LineVideo.vue'
import NumberGrowWarp from '@/components/number-grow-warp/NumberGrowWarp.vue'
import type { CountryQhList } from '@/types/baseTypes'
import { ArrowRight } from '@element-plus/icons-vue'
import { reverse, sortBy } from 'lodash'
import * as mapboxgl from 'mapbox-gl'
import { onMounted, ref } from 'vue'
import TicketGetComp from './components/TicketGetComp.vue'
import TicketQuantityComp from './components/TicketQuantityComp.vue'
import { iconHong, iconHu, iconLv } from './icons'

const showGetCheck = ref(true)
const showMapOrder = ref(false)
const videoUrl = ref('')
const businessPoint = [
  [120.593118, 31.137392],
  [120.68526, 31.154798],
  [120.84756, 31.036854],
  [120.609815, 30.902274],
  [120.537092, 31.01257],
  [120.610072, 31.133058],
  [120.675382, 31.067423],
  [120.386564, 30.944182],
  [120.498901, 30.809329],
  [120.500311, 30.816125],
  [120.536937, 30.860828],
  [120.512368, 30.899803],
  [120.639596, 30.973584],
  [120.639247, 31.029475],
  [120.644533, 30.947505]
]
const tabs = ref([
  { icon: ic_huang, label: '政务服务中心', value: 0 },
  { icon: ic_lv, label: '便民服务中心', value: 0 },
  { icon: ic_zong, label: '企业服务中心', value: 15 }
])
const todayCount = ref(0)
onMounted(() => {
  initData()
})
const initData = () => {
  requestApi.GetCountryQhInfo().then((res) => {
    tabs.value[0].value = res.zwfwCenterCount
    tabs.value[1].value = res.bmCenterCount
    todayCount.value = res.todayCount
    points.value = reverse(sortBy(res.list, 'code'))
    initMapChart()
  })
  // setInterval(() => {
  //   requestApi.GetCountryQhInfo().then((res) => {
  //     todayCount.value = res.todayCount
  //     points.value = reverse(sortBy(res.list, 'code'))
  //     updateMarker()
  //   })
  // }, 5000)
}
const points = ref<CountryQhList[]>([])
let map: mapboxgl.Map
const showDialog = ref(false)
const initTable = () => {
  showDialog.value = true
}
const returnToNormal = () => {
  map.flyTo({
    center: { lng: 120.61524704098707, lat: 30.741558529488515 }, // starting position [lng, lat]
    zoom: 9.90847312840893, // starting zoom
    bearing: 0,
    pitch: 61.98646986469853
  })
}
const initMapChart = () => {
  map = new mapboxgl.Map({
    accessToken:
      'pk.eyJ1IjoienJzd3lsIiwiYSI6ImNrZDhrOXcwZTJrZmsycnE5cmFyN3lwNjkifQ.xAb-Huux08WSEOXjHQFZZA',
    container: 'map', // container ID
    style: {
      version: 8,
      sources: {},
      layers: [],
      glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'
    }, // style URL
    center: { lng: 120.60756448235185, lat: 30.76206037646439 }, // starting position [lng, lat]
    zoom: 10.5, // starting zoom
    bearing: 0,
    pitch: 61.98646986469853
  })

  let ic_lv_Icon = new Image(160, 200)
  ic_lv_Icon.src = 'data:image/svg+xml;base64,' + window.btoa(iconLv)
  ic_lv_Icon.onload = () => {
    map.addImage('ic_lv', ic_lv_Icon)
  }

  let ic_hong_Icon = new Image(160, 200)
  ic_hong_Icon.src = 'data:image/svg+xml;base64,' + window.btoa(iconHong)
  ic_hong_Icon.onload = () => {
    map.addImage('ic_hong', ic_hong_Icon)
  }

  let ic_huang_Icon = new Image(160, 200)
  ic_huang_Icon.src = 'data:image/svg+xml;base64,' + window.btoa(iconHu)
  ic_huang_Icon.onload = () => {
    map.addImage('ic_huang', ic_huang_Icon)
  }

  map.on('load', () => {
    map.addSource('maine', {
      type: 'geojson',
      data: wuJiangJson as any
    })

    map.addLayer({
      type: 'line',
      source: 'maine',
      id: 'line-background',
      paint: {
        'line-color': '#0fe2df',
        'line-width': 3,
        'line-opacity': 1
      }
    })
    map.addLayer(
      {
        id: 'maine',
        type: 'fill-extrusion',
        source: 'maine', // reference the data source
        layout: {},
        paint: {
          'fill-extrusion-color': [
            'interpolate',
            ['exponential', 0.99],
            ['get', 'areaId'],
            0,
            '#328bd5',
            6,
            '#00eab3',
            12,
            '#328bd5'
          ],
          'fill-extrusion-opacity': 1,
          'fill-extrusion-height': 1000
        }
      },
      'line-background'
    )

    map.addLayer({
      id: 'cluster-count',
      type: 'symbol',
      source: 'maine',
      layout: {
        'text-field': ['get', 'name'],
        'text-size': 12,
        'text-font': ['AlibabaPuHuiTi-3-75-SemiBold'],
        'text-allow-overlap': true
      },
      paint: {
        'text-color': '#fff',
        'text-halo-color': '#011a30',
        'text-halo-width': 1
      }
    })

    const features = points.value.map((e) => {
      return {
        type: 'Feature',
        properties: e,
        geometry: {
          type: 'Point',
          coordinates: [parseFloat(e.longitude), parseFloat(e.latitude)]
        }
      }
    })
    const businessPoints = businessPoint.map((e) => {
      return {
        type: 'Feature',
        properties: e,
        geometry: {
          type: 'Point',
          coordinates: e
        }
      }
    })

    map.addLayer({
      id: 'earthquakes-layer',
      type: 'symbol',
      source: {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: businessPoints
        } as GeoJSON.GeoJSON
      },
      layout: {
        'icon-offset': [200, 50],
        'icon-image': 'ic_hong',
        'icon-size': ['interpolate', ['linear'], ['zoom'], 9, 0.07, 17, 0.21],
        'icon-allow-overlap': true
      }
    })

    map.addLayer(
      {
        id: 'points',
        type: 'symbol',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: features
          } as GeoJSON.GeoJSON
        },
        layout: {
          'icon-image': [
            'match',
            ['get', 'code'],
            'normal',
            'ic_hong',
            'safe',
            'ic_lv',
            'danger',
            'ic_hong',
            '320509',
            'ic_huang',
            'ic_lv'
          ],
          'icon-size': ['interpolate', ['linear'], ['zoom'], 9, 0.1, 17, 0.3],
          'icon-allow-overlap': true
        }
      },
      'earthquakes-layer'
    )
    let tmout: number
    let inMarker: mapboxgl.Marker
    map.on('mouseenter', 'points', (e) => {
      map.getCanvas().style.cursor = 'pointer'
      if (e.features) {
        clearTimeout(tmout)
        if (inMarker) inMarker.remove()
        const valPoint = e.features[0].properties as CountryQhList
        const el = document.createElement('div')
        videoUrl.value = valPoint.szrurl
        regionName.value = valPoint.name
        el.innerHTML = getContent(valPoint)
        const numberDom = el.querySelector('.hover-qu') as HTMLDivElement
        numberDom.onclick = () => {
          selectPoint.value = valPoint
          const selectItem = townList.find((e) => e.name == valPoint.name)
          selectPointID.value = selectItem ? selectItem.zqrowguid : ''
          showMapOrder.value = true
        }
        el.onclick = () => {
          console.log('父点击')
          const mk = inMarker.getElement().querySelector('.hover-marker') as HTMLElement
          if (mk.style.opacity != '0') {
            mk.style.opacity = '0'
          }
          tmout = setTimeout(() => {
            inMarker.remove()
          }, 500)
          return
        }
        inMarker = new mapboxgl.Marker({
          element: el,
          anchor: 'bottom'
        })
          .setLngLat([parseFloat(valPoint.longitude), parseFloat(valPoint.latitude)])
          .addTo(map)
      }
    })

    map.on('mouseleave', 'points', () => {
      map.getCanvas().style.cursor = ''
    })

    map.on('click', 'points', (e) => {
      if (e.features) {
        const valPoint = e.features[0].properties as CountryQhList
        if (valPoint.name.indexOf('平望') === -1 && valPoint.name.indexOf('桃源') === -1) {
          initTable()
        }
      }
    })
    updateMarker()
  })
}

const getContent = (params: CountryQhList) => {
  return `
  <div class="hover-marker">
    <div class="hover-title">${params.name}</div>
    <div class="hover-body">
      <div class="hover-qu">
        <div><div>取号量</div><div><span>${params.value}</span>个</div></div>
        <div><div>占全区</div><div><span>${params.prop}</span>%</div></div>
      </div>
    </div>
  </div>`
}
let mkList: mapboxgl.Marker[] = []
const updateMarker = () => {
  mkList.forEach((e) => {
    e.remove()
  })
  mkList = []
  points.value.forEach((item) => {
    const el = document.createElement('div')
    const width = '10px'
    const height = '10px'
    el.style.width = `${width}px`
    el.style.height = `${height}px`
    el.innerHTML = `<div class="marker ${item.code.length == 6 ? 'marker-center' : ''}">${item.value}</div>`
    const mk = new mapboxgl.Marker({
      element: el,
      anchor: 'bottom'
    })
      .setLngLat([parseFloat(item.longitude), parseFloat(item.latitude)])
      .addTo(map)
    mkList.push(mk)
    // }
  })
}

//弹窗内逻辑 加载图表
const selectPoint = ref<CountryQhList>()
const selectPointID = ref('')
const regionName = ref('')
const selectName = ref('')

const townList = [
  {
    name: '江陵街道便民服务中心',
    zqrowguid: '24b3f65d-6320-489f-a49d-ed385d95058f'
  },
  {
    name: '八坼街道便民服务中心',
    zqrowguid: '26bae9e2-e269-42ca-95cb-53d0bf23f884'
  },
  {
    name: '平望镇便民服务中心',
    zqrowguid: '28e1164b-1bc2-4619-8af0-6977907a9c33'
  },
  {
    name: '汾湖便民服务中心',
    zqrowguid: '46bab9c4-5454-4caf-93c0-5beb386a48b9'
  },
  {
    name: '同里镇便民服务中心',
    zqrowguid: '4da0ed47-c3b8-4b62-ac86-aa65f5551daf'
  },
  {
    name: '横扇街道便民服务中心',
    zqrowguid: '7ef146be-ad0b-48a9-b759-add2a9e7b414'
  },
  {
    name: '七都镇便民服务中心',
    zqrowguid: '840c0e8a-f3d0-4118-9801-6550c6ebac84'
  },
  {
    name: '盛泽镇便民服务中心',
    zqrowguid: '88763d21-450c-44aa-8fa8-25f06926acab'
  },
  {
    name: '桃源镇便民服务中心',
    zqrowguid: 'b919f68e-80db-4219-93f3-6a11b8ca3df8'
  },
  {
    name: '震泽镇便民服务中心',
    zqrowguid: 'cce5bc0b-684b-4252-839f-ccac80dbaa5f'
  },
  {
    name: '吴江区政务服务中心',
    zqrowguid: 'ce78a5b4-3daa-4ba3-95ae-c9969bb57b8b'
  },
  {
    name: '松陵街道便民服务中心',
    zqrowguid: 'eb941d64-553a-4c98-b752-d6468ef1854d'
  },
  {
    name: '吴江经济技术开发区便民服务中心',
    zqrowguid: 'ffcce7e2-4915-4373-86e7-73f798e28dac'
  }
]
</script>
<style scoped lang="less">
.table {
  --el-table-tr-bg-color: #19aeef20;
  --el-table-header-bg-color: #0a577b;
  --el-fill-color-lighter: #0000;
  --el-table-header-text-color: #fff;
}
/* @import url(); 引入css类 */

.orderBody-item {
  transition: all 0.5s;
  border-radius: 1rem;
  &:hover {
    cursor: pointer;
    background-color: #0a577b
    // background: linear-gradient(90deg, #0a577b, #0000);
  }
   &:active{
    cursor: pointer;
    background-color: #0000;
    // background: linear-gradient(90deg, #0a577b, #0000);
  }
}
</style>
